package top.szhome.gateway.fileter;

//import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import top.szhome.framework.core.tools.constant.AuthConstant;
import top.szhome.framework.core.tools.support.Resp;
import top.szhome.framework.core.tools.util.StringUtil;
//import top.szhome.framework.starter.jwt.JwtUtil;
import top.szhome.gateway.util.WebUtil;

/**
 * 权限认证过滤器
 *
 * @author 唐加利
 * @date 2023/8/17
 **/
public class AuthFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 跳过权限认证的请求
        String url = WebUtil.getOriginalRequestUrl(exchange);
        if(skip(url)){
            return chain.filter(exchange);
        }

        // 获取Token
        String token = getToken(exchange);
        if(StringUtil.isBlank(token)){
            return WebUtil.render(exchange, Resp.fail("401", "您未提供访问令牌，无权访问"));
        }

        // 错误token格式
        if(!StringUtil.startsWith(token.toLowerCase(), AuthConstant.AUTH_TOKEN_PREFIX)){
            return WebUtil.render(exchange, Resp.fail("401", "访问令牌格式错误，应以Bearer开头"));
        }

        // 获取真正的token
        token = token.substring(AuthConstant.AUTH_TOKEN_PREFIX.length());
//        Claims claims = JwtUtil.parseJWT(token);
//        if(claims == null){
//            return WebUtil.render(exchange, Resp.fail("401", "访问令牌无效，无权访问"));
//        }

        // TODO redis检查token是否已退出
        return chain.filter(exchange);
    }

    public boolean skip(String url){
        return true;
    }

    /**
     * 获取Token，优先级：Header -> Cookie -> Parameter
     * @param exchange
     * @return
     */
    private String getToken(ServerWebExchange exchange){
        String token = WebUtil.getHeader(exchange, AuthConstant.AUTH_TOKEN_HEADER);

        if(StringUtil.isBlank(token)){
            token = WebUtil.getCookie(exchange, AuthConstant.AUTH_TOKEN_HEADER);
        }

        if(StringUtil.isBlank(token)){
            token = WebUtil.getParam(exchange, AuthConstant.AUTH_TOKEN_HEADER);
        }

        return token;
    }

}
